package net.roobook.cms.modules.admin.controller;

import net.roobook.cms.common.annotation.Log;
import net.roobook.cms.common.annotation.Log.OperatorType;
import net.roobook.cms.common.constant.BaseConstant;
import net.roobook.cms.common.entity.StateCodeEnum;
import net.roobook.cms.common.exception.CmsException;
import net.roobook.cms.common.exception.XssAndSqlException;
import net.roobook.cms.common.web.BaseController;
import net.roobook.cms.modules.admin.entity.SysSetting;
import net.roobook.cms.modules.admin.service.SysLoggerService;
import net.roobook.cms.modules.admin.service.SysSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author cos
 * @email 327878610@qq.com
 * @link https://roobook.net
 * @Description 系统配置
 * @date 2023/10/11 8:35
 **/
@Controller
@RequestMapping("admin/system")
public class SysSettingController extends BaseController {
    @Autowired
    private SysSettingService sysSettingService;
    /**
     * 首页跳转
     * @return
     */
    @Log(operType = OperatorType.SELECT, module = "系统设置", content = "查询系统设置")
    @RequestMapping({"","toIndex"})
    public String toIndex(Model model) {
        SysSetting system = sysSettingService.getSystem();
        model.addAttribute("system", system);
        return "admin/system/system";
    }


    /**
     * 更新
     * @return
     * @throws CmsException
     */
    @Log(operType = OperatorType.UPDATE, module = "系统设置", content = "修改系统设置")
    @RequestMapping("update")
    public String update(SysSetting system) throws CmsException {
        Pattern pattern = Pattern.compile(BaseConstant.FILE_NAME_REGEXP);
        Matcher uploadDirMatcher = pattern.matcher(system.getUploaddir());
        if(uploadDirMatcher.find()) {
            throw new XssAndSqlException(
                    StateCodeEnum.XSS_SQL_EXCEPTION.getCode(),
                    StateCodeEnum.XSS_SQL_EXCEPTION.getDescription(),
                    "默认上传目录名疑似不安全，详情：" + system.getUploaddir());
        }
        Matcher staticDirmatcher = pattern.matcher(system.getStaticdir());
        if(staticDirmatcher.find()) {
            throw new XssAndSqlException(
                    StateCodeEnum.XSS_SQL_EXCEPTION.getCode(),
                    StateCodeEnum.XSS_SQL_EXCEPTION.getDescription(),
                    "默认静态化目录名疑似不安全，详情：" + system.getStaticdir());
        }
        int num = sysSettingService.update(system);
        return "redirect:/admin/system/toIndex";
    }
}
